<template>
  <view class="weachat-circle-container">
    <view class="weachat-circle-input-content">

      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/word.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">专辑名称</view>
        </view>
        <view class="title-tips">*专辑名称字数最多10字/必填</view>
      </view>

      <!-- content -->
      <view class="circle-content">
        <view style="height: 100%;width: 100%;overflow-y: auto">
          <input
            v-model="album_name"
            placeholder="请填写专辑名称（必填）"
            placeholder-style="fontSize:24rpx"
            :auto-height="false"
            class="circle-input"
            maxlength="10" />
        </view>
        <view class="word-length">{{ album_name.length }}/10</view>
      </view>

      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/class.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">课程链接</view>
        </view>
        <view class="title-tips">*教程、课程链接/选填</view>
      </view>

      <!-- content -->
      <view class="circle-content">
        <view style="height: 100%;width: 100%;overflow-y: auto">
          <input
            v-model="class_url"
            placeholder="请填写教程、课程链接（选填）"
            placeholder-style="fontSize:24rpx"
            :auto-height="false"
            class="circle-input"
            />
        </view>
      </view>

      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/cate.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">选择分类</view>
        </view>
        <view class="title-tips">*选择所属分类/必填</view>
      </view>

      <view class="type-list-container flex ac jb">
        <view
          v-for="item in artworksTypeList"
          :key="item.value"
          class="type-list-item flex ac jc"
          :class="{
            active: item.value === currentType
          }"
          @click="currentType = item.value">{{ item.label }}</view>
      </view>

      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/photo.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">上传图片</view>
        </view>
        <view class="title-tips">*最多100张图，至少1张图,长按拖动排序</view>
      </view>

      <!-- upload photo -->
      <view class="upload-photo-content">
        <ImageList
          v-model="list"
          keyName="cover_url"
          :cols="4"
          :borderRadius="16"
          :number="100"
          :upload-config-props="uploadConfig">
        </ImageList>
      </view>

      <!-- upload btn -->
      <!-- 上传按钮确定 -->
      <view class="confirm-btn">
        <u-button
          class="btn"
          type="primary"
          shape="circle"
          hover-class="none"
          :custom-style="{
            backgroundColor: '#56d39d',
            fontWeight: 700
          }"
          @click="sumbitArtworks"
          :loading="btnLoading">确定上传</u-button>
      </view>
      
    </view>

    <!-- 海报 -->
    <lPainter
      :board="posterObj"
      ref="painter"
      @success="createPosterSuccess"
      :is-render-image="true"></lPainter>
  </view>
</template>

<script>
  import { getAliyunCosSignature } from '@/api/applet';
  import { checkText } from '@/utils/index';
  import { createArtworksMaterialAlbum, artworksMaterialAlbumInfoById } from '@/api/artworks';
  import ImageList from './components/imageList.vue';
  import lPainter from '@/components/limePainter/index.vue';
  import { mapGetters } from 'vuex';
  import config from '@/utils/config';
  export default {
    components: {
      ImageList,
      lPainter
    },
    data() {
      return {
        album_name: '',
        class_url: '',
        list: [],
        uploadConfig: null,
        uploadNumConfig: {
          max_upload_num: 0,
          surplus: 0,
          todayUploadNum: 0
        },
        btnLoading: false,
        agreement: true,
        posterObj: {
					width: '680rpx',
					height: '1188rpx',
					background: '#fff',
					borderRadius: '16rpx',
					views: []
				},
        imageBase64: '',
        uploadAction: `${config.baseApi}/client/upload/aliyunUpload`,
        author_id: '',
        id: '',
        artworksTypeList: [{
          value: 1,
          label: '壁纸'
        },
        {
          value: 2,
          label: '头像'
        },
        {
          value: 3,
          label: '表情包'
        },
        {
          value: 6,
          label: '背景图'
        }],
        currentType: 1,
        current_id: ''
      }
    },
    computed: {
      ...mapGetters([
        'userInfo',
        'token'
      ])
    },
    watch: {
      list: {
        handler(val) {
          console.log(val)
        }
      }
    },
    onLoad(options) {
      this.current_id = options.current_id || '';
      if (options.current_id) {
        this.getArtworksMaterialAlbumInfoById();
      }
      this.getAliyunCosSignature();
    },
    methods: {

      // 获取作品信息
      getArtworksMaterialAlbumInfoById() {
        artworksMaterialAlbumInfoById({
          id: this.current_id
        }).then(result => {
          if (result && result.data) {
            let data = result.data;
            this.album_name = data.album_name;
            this.currentType = data.type;
            this.list = data.image_list;
            this.class_url = data.class_url;
          }
        });
      },

      // 获取阿里云配置
      getAliyunCosSignature() {
        getAliyunCosSignature({
          dir: 'wechatcircle'
        }).then(result => {
          if (result && result.data) {
            this.uploadConfig = result.data;
          }
        });
      },

      // 确定提交
      async sumbitArtworks() {

        // 专辑名称
        if (!this.album_name) {
          uni.showToast({
            title: '请输入专辑名称',
            icon: 'none',
            mask: false,
          })
          return;
        }

        // 上传图片素材
        if (this.list && this.list.length === 0) {
          uni.showToast({
            title: '请上传图片素材',
            icon: 'none',
            mask: false,
          })
          return;
        }

        let image_list = this.list.map(item => {
          return {
            cover_url: item.cover_url,
            wx_cover_url: `${item.cover_url}?x-oss-process=image/resize,w_360`
          }
        })

        // 检查文本内容
        const flag = await checkText(this.album_name);
        if (flag) {
          this.btnLoading = true;
          createArtworksMaterialAlbum({
            album_name: this.album_name,
            type: this.currentType,
            image_list,
            id: this.current_id || '',
            class_url: this.class_url
          }).then(result => {
            if (result && result.code === 200) {
              uni.showToast({
                title: '操作成功！',
                icon: 'success',
                mask: false,
              });
              setTimeout(() => {
                location.reload();
              }, 1500);
            }
          })
        }
      },

      // 转成file对象
			async dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				let fileType = mime.split('/');
				return new File([u8arr], `${filename}${fileType.length > 1 ? '.' + fileType[1] : ''}`, { type: mime });
			},

      // 前往同意
      handleAgreement() {
        uni.navigateTo({ url: '/pages/about/agreement' })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .weachat-circle-container{
    padding: 24rpx 0;

    .type-list-container{
      padding: 12rpx 32rpx;
      margin-bottom: 24rpx;

      .type-list-item{
        background-color: #fff;
        padding: 12rpx 24rpx;
        border-radius: 8rpx;
        min-width: 23%;
      }

      .type-list-item.active{
        background-color: $uni-color-primary;
        color: #fff;
      }
    }

    .w-title{
      margin-bottom: 24rpx;
      padding: 0 24rpx;
    }

    .title-content{
      .word-icon{
        width: 40rpx;
        height: 40rpx;
      }

      .title-text{
        font-size: 30rpx;
        font-weight: bold;
        margin-left: 8rpx;
      }
    }

    .title-tips{
      font-size: 22rpx;
      color: #666;
    }

    .circle-content{
      margin: 0 auto;
      width: calc(100% - 48rpx);
      height: 128rpx;
      background: #fafafc;
      border: 2rpx solid #eee;
      border-radius: 10rpx;
      padding: 30rpx;
      position: relative;
      margin-bottom: 32rpx;

      .circle-input{
        font-size: 24rpx;
        width: 100%;
      }

      .word-length{
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 24rpx;
        text-align: right;
        font-size: 26rpx;
        color: #67676a;
        line-height: 36rpx;
        padding-right: 30rpx;
      }
    }

    .upload-photo-content{
      margin-bottom: 32rpx;
    }

    .confirm-btn{
      padding: 24rpx;
    }

    .create-album{
      position: absolute;
      right: 0;
      top: 0;
      margin: auto;
      font-size: 26rpx;
      font-weight: 400;
      color: $uni-color-primary;
      background: #f3f7fb;
      padding: 6rpx 24rpx;
      border-radius: 24rpx;
    }

    .agreement{
      margin-top: 24rpx;
      font-size: 24rpx;
    }
  }
</style>
